//
//  MineRefundViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/10/30.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "MineRefundViewController.h"
#import "SelectPictureView.h"
#import "RefundingViewController.h"

@interface MineRefundViewController ()<UIPickerViewDelegate, UIPickerViewDataSource>
{
    NSMutableArray *_images;
    NSMutableArray *_reasonArr;
    NSMutableArray *_reasonIdArr;
}
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *refundBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIView *pictureBackView;

@property (strong, nonatomic) SelectPictureView *pictureView;

@property (strong, nonatomic) UIPickerView *pickerView;
@property (strong, nonatomic) UIButton *canceBtn;
@property (strong, nonatomic) UIView *BtnbackView;
@property (copy, nonatomic) NSString *ChooseReasonId;
@end

@implementation MineRefundViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"退款";
    self.view.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    _images = [NSMutableArray array];
    _reasonArr = [NSMutableArray array];
    _reasonIdArr = [NSMutableArray array];
    
    _priceLabel.layer.borderColor = [[UIColor colorWithHex:0xe4e4e4]CGColor];
    _priceLabel.layer.borderWidth = 1.0f;
    [_priceLabel.layer setCornerRadius:3.0];
    _priceLabel.layer.masksToBounds = YES;
    _priceLabel.text = [NSString stringWithFormat:@"  ￥%@", _moneyStr];
    
    _refundBtn.layer.borderColor = [[UIColor colorWithHex:0xe4e4e4]CGColor];
    _refundBtn.layer.borderWidth = 1.0f;
    [_refundBtn.layer setCornerRadius:3.0];
    _refundBtn.layer.masksToBounds = YES;
    
    [self getPictures];
    
    for (NSDictionary *dic in [self.reasonDic allValues]) {
        [_reasonArr addObject:dic[@"dataName"]];
        [_reasonIdArr addObject:dic[@"dataVal"]];
    }
}

#pragma mark- 上传图片
- (void)getPictures
{
    // 1.获得图片
    _pictureView = [[SelectPictureView alloc]initWithFrame:CGRectMake(0, 50, WIDTH, 80)];
    [_pictureBackView addSubview:_pictureView];
    self.pictureView.maxImageCount = 3;
    self.pictureView.ratioOfWidthAndHeight = 240.0/240.0;
    __weak typeof(self) weakSelf = self;
    self.pictureView.getImageBlock = ^(NSMutableArray *ImageArr){
        
        NSLog(@"ImageArr ======= %lu", (unsigned long)ImageArr.count);
        weakSelf.pictureView.height = 80;
        [weakSelf.view loadingOnAnyView];
        for (NSDictionary *dic in ImageArr) {
            if ([dic[@"image"] isKindOfClass:[NSData class]]) {
                [weakSelf uploadIma:dic[@"image"]];
            }
        }
    };
    
}
- (void)uploadIma:(NSData *)data
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    
    NSDictionary *dic = @{@"name":@"file",@"type":@"image/png",@"tmp_name":fileName,@"size":@(data.length)};
    NSDictionary *para = @{@"upload_file":@[dic], @"userToken":[Utils getUserToken]};
    [THWManager PostImageWithData:API(MineRefundAddImg) imageData:data otherParamters:para success:^(NSURLSessionDataTask *task, id responseObject) {
        [_images addObject:responseObject[@"data"][@"msg"]];
        [self.view removeAnyView];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.view removeAnyView];
    }];
}
- (IBAction)refundClick:(UIButton *)sender {
    if (_pickerView) {
        _BtnbackView.hidden = NO;
        _pickerView.hidden = NO;
    }else{
        [self createPickerView];
    }
}

- (void)createPickerView
{
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT-200, WIDTH, 200)];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.backgroundColor = [UIColor colorWithHex:0x999999];
    [_pickerView selectRow:0 inComponent:0 animated:YES];
    [self.view addSubview:_pickerView];
    
    _BtnbackView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT-230, WIDTH, 30)];
    _BtnbackView.backgroundColor = [UIColor colorWithHex:0x999999];
    [self.view addSubview:_BtnbackView];
    
    _canceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _canceBtn.frame = CGRectMake(10, 10, 50, 20);
    [_canceBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_canceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_canceBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [_BtnbackView addSubview:_canceBtn];
}

- (void)btnClick
{
    _BtnbackView.hidden = YES;
    _pickerView.hidden = YES;
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _reasonArr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *str = _reasonArr[row];
    return str;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [_refundBtn setTitle:[NSString stringWithFormat:@"  %@", _reasonArr[row]] forState:UIControlStateNormal];
    _ChooseReasonId = [NSString stringWithFormat:@"%@", _reasonIdArr[row]];
    [_refundBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
}

- (IBAction)submitClick:(UIButton *)sender {
    
    if (_ChooseReasonId) {
        [self.view loadingOnAnyView];
        NSDictionary *dic = @{@"reason":_ChooseReasonId, @"userToken":[Utils getUserToken], @"img":[_images componentsJoinedByString:@","], @"money":_moneyStr, @"type":@"shop", @"orderId":self.orderId};
        [THWManager PostHttp:API(MineOrderRefundClick) Parameters:dic Success:^(id responseObject) {
            [self.view removeAnyView];
            if ([String(responseObject[@"status"]) isEqualToString:@"-1"]) {
                [self.view Message:responseObject[@"msg"]];
            }else{
                [self.view Message:responseObject[@"msg"]];
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"OrderRefresh" object:nil];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } andFalse:^(NSError *error) {
            [self.view removeAnyView];
        }];
    }else{
        [self.view Message:@"请选择退货原因"];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
